package org.grow.later.score;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.*;

import javax.transaction.Transactional;
import java.util.HashMap;
import java.util.Map;

@RestController
public class ScoreController {
    @Autowired
    private ScoreJpa scoreJpa;
    @PostMapping("/score/")
    public StudentScore createScore(@RequestBody StudentScore studentScore){
        //拒绝前端传入的任何Id 保证后端自动生成
        studentScore.setScoreId(null);
        //后端业务逻辑自行计算
        studentScore.setAverageScore(studentScore.calculateAverage());
        return scoreJpa.save(studentScore);
    }
    //restful 规范 全修改用put 部分修改用patch
    @PutMapping("/score/")
    public StudentScore updateScore(@RequestBody StudentScore studentScore){
        StudentScore temp = scoreJpa.findByScoreId(studentScore.getScoreId());
        if (temp!=null){
                  studentScore.setAverageScore(studentScore.calculateAverage());
                  return scoreJpa.save(studentScore);
        }
        throw new RuntimeException(studentScore.getScoreId()+" 资源不存在");
    }
    @GetMapping("/score/{scoreId}")
    public StudentScore findScore(@PathVariable Long scoreId){
        return scoreJpa.findByScoreId(scoreId);
    }
    @GetMapping("/scores")
    public Map<String,Object> fetchScores(@RequestParam int pageNum, @RequestParam int pageSize){
        Page<StudentScore> all = scoreJpa.findAll(PageRequest.of(
                pageNum - 1, pageSize));
        return new HashMap<String,Object>(){{
            put("total",all.getTotalElements());
            put("resultList",all.getContent());
        }};
    }
    @DeleteMapping("/scores")
    @Transactional
    public Long deleteAll(){
        long a = scoreJpa.count();
        scoreJpa.deleteAll();
        return a;
    }


}
